package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpOrDownMess;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsContentVO;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl  extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 查询文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {

        //1.检查参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();
        //获取当前登录人的信息
        WmUser user = WmThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.分页条件查询
        IPage page = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //状态精确查询
        if(dto.getStatus() != null){
            lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }

        //频道精确查询
        if(dto.getChannelId() != null){
            lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        //时间范围查询
        if(dto.getBeginPubDate()!=null && dto.getEndPubDate()!=null){
            lambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }

        //关键字模糊查询
        if(StringUtils.isNotBlank(dto.getKeyword())){
            lambdaQueryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }

        //查询当前登录用户的文章
        lambdaQueryWrapper.eq(WmNews::getUserId,user.getId());

        //发布时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        page = page(page,lambdaQueryWrapper);

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult((int) page.getCurrent(),
                (int) page.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }


    /**
     * 发布修改文章或保存为草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {

        //1.接收参数
        WmNews wmNews = new WmNews();
        //2.获取内容中的图片URL
        String content = dto.getContent();
        Set<String> urls = new HashSet<>();
        List<WmNewsContentVO> wmNewsContentVOS =
                JSON.parseArray(content, WmNewsContentVO.class);
        //遍历内容中的集合，获取image图片的url加入到hashset中
        if (!CollectionUtils.isEmpty(wmNewsContentVOS)) {
            for (WmNewsContentVO wmNewsContentVO : wmNewsContentVOS) {
                if (WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(wmNewsContentVO.getType())) {
                    String value = wmNewsContentVO.getValue();
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(value)) {
                        urls.add(value);
                    }
                }
            }
        }

        List<String> urlList = new ArrayList<>(urls);
        //3.自动选择封面
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            int size = urls.size();
            if (size >= 3) {
                dto.setImages(urlList.subList(0, 3));
                dto.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else if (size > 0) {
                dto.setImages(urlList.subList(0, 1));
                dto.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else {
                dto.setImages(null);
                dto.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
        }
        BeanUtils.copyProperties(dto, wmNews);

        //4.将封面图片手动处理
        if (!CollectionUtils.isEmpty(dto.getImages())) {
            wmNews.setImages(org.apache.commons.lang3.StringUtils.join(dto.getImages(), ","));
        }

        //5.保存
        wmNews.setSubmitedTime(new Date());
        if (dto.getId() != null) {
            //删除文章和素材关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, dto.getId()));
            //更新
            updateById(wmNews);
        } else {
            //新增
            wmNews.setEnable((short) 1);
            wmNews.setCreatedTime(new Date());
            wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
            save(wmNews);
        }
        //6.判断是草稿直接返回
        if (Objects.equals(dto.getStatus(),WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //7.保存内容和封面中的素材和文章的关联关系
        saveMaterialAndNewsIdRelation(urlList, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        saveMaterialAndNewsIdRelation(dto.getImages(), wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);

        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3.判断文章是否已发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前文章不是发布状态，不能上下架");
        }

        //4.修改文章enable
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable,dto.getEnable())
                    .eq(WmNews::getId,wmNews.getId()));
        }

        //发送消息，通知article端修改文章配置
        if(wmNews.getArticleId() != null){
            UpOrDownMess msg = new UpOrDownMess();
            msg.setArticleId(wmNews.getArticleId());
            msg.setEnable(dto.getEnable());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(msg));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    public void saveMaterialAndNewsIdRelation(List<String> urls, int newsId, short type) {
        if (CollectionUtils.isEmpty(urls)) {
            return;
        }
        //url转换成id
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, urls).select(WmMaterial::getId));
        List<Integer> ids = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
        if (urls.size() != ids.size()) {
            throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
        }

        wmNewsMaterialMapper.saveRelations(ids, newsId, type);
    }

}